import { useCallback, useEffect, lazy } from "react";
import { ErrorBoundary } from "react-error-boundary";

import useLoginStore from "@/store/login";

const PageError = lazy(() => import("@/pages/404/NotFound")); // 404页面
import { useRouter } from "../hooks/use-route";

type Props = {
  children: React.ReactNode;
};
export default function ProtectedRoute({ children }: Props) {
  const router = useRouter();
  const { token } = useLoginStore();

  const check = useCallback(() => {
    if (!token) {
      router.replace("/login");
    }
  }, [router, token]);

  useEffect(() => {
    check();
  }, [check]);

  return (
    <ErrorBoundary FallbackComponent={PageError}>{children}</ErrorBoundary>
  );
}
